/* "let" are variables that change
 "const" are variables that do not change
 Setting a variable type to "null" is used in situations 
where it needs to be cleared/not be used.
*/

var dragBox = document.querySelector(".dragbox");
new Sortable(dragBox, {
	animation: 250,
});

const dropzoneupload = document.querySelector(".dropzoneupload");

// Marks zone as hover
dropzoneupload.addEventListener("dragover", (e) => {
	dropzoneupload.classList.add("hoverdropz");
	e.preventDefault();
	console.log("test");
});

// Marks zone as unhovered
dropzoneupload.addEventListener("dragleave", () => {
	dropzoneupload.classList.remove("hoverdropz");
});

// Listen for filedrop
dropzoneupload.addEventListener("drop", (e) => {
	e.preventDefault();
	const image = e.dataTransfer.files[0];
	const type = image.type;
	console.log(type);

	//Get all elements within this class as an array.
	const listImg = document.querySelectorAll(".imgcell");
	const filledPictures = document.querySelectorAll(".picturefill");
	console.log(listImg);

	if (filledPictures.length == 5) {
		dropzoneupload.classList.remove("hoverdropz");
		dropzoneupload.setAttribute("class", "dropzoneupload fullImages");
		dropzoneupload.innerText = "All cells are filled with images.. Clear all by pressing the X button!";
		// Accept only specific image filetypes
	} else if (type == "image/png" || type == "image/jpeg" || type == "image/gif") {
		dropzoneupload.setAttribute("class", "dropzoneupload validimg");
		dropzoneupload.innerText = "Added " + image.name;
		// Load image data
		let fileReader = new FileReader();

		fileReader.onload = () => {
			// Fill image inside an empty cell.
			let fileURL = fileReader.result;
			let imgTag = `<img class="picturefill" src="${fileURL}" alt="${image.name}">`;

			for (let i = 0; i < listImg.length; i++) {
				// Dynamically check if imgcell indices contain pictures and fill pictures in accordingly.
				if (!listImg[i].contains(filledPictures[i])) {
					listImg[i].innerHTML = imgTag;
					console.log(filledPictures);
					break;
				}
			}

			console.log(fileURL);
		};
		fileReader.readAsDataURL(image);
	} else {
		dropzoneupload.setAttribute("class", "dropzoneupload invalidimg");
		dropzoneupload.innerText = "Invalid filetype.. Try again?";
		return false;
	}
});

// If the button is pressed, clear all images on the list.
function clearButton() {
	const btn = document.getElementsByClassName("picturefill");
	while (btn[0]) {
		btn[0].parentNode.removeChild(btn[0]);
	}
	dropzoneupload.setAttribute("class", "dropzoneupload");
	dropzoneupload.innerText = "Drop image here. Filetypes accepted: .PNG, .JPG, .APNG, .GIF";
}
